using System;
using Scenes.Msg;
using UnityEngine.SceneManagement;

namespace Scenes
{
    public class SceneMgr : ManagerBase
    {
        public static SceneMgr Instance = null;

        private void Awake()
        {
            Instance = this;
            SceneManager.sceneLoaded += SeceneManager_sceneLoaded;
            Add(SceneEvent.LOAD_SCENE, this);
        }


        public override void Execute(int eventCode, object message)
        {
            switch (eventCode)
            {
                case SceneEvent.LOAD_SCENE:
                    LoadSceneMsg sceneMsg = message as LoadSceneMsg;
                    loadScene(sceneMsg);
                    break;
            }
        }

        /**
         * 用来控制场景
         */
        private SceneManager _sceneManager;

        private Action _onSceneLoaded = null;


        private void loadScene(LoadSceneMsg sceneMsg)
        {
            if (sceneMsg.SceneBuildIndex != -1)
            {
                SceneManager.LoadScene(sceneMsg.SceneBuildIndex);
            }

            else if (sceneMsg.SceneBuildName != null)
            {
                SceneManager.LoadScene(sceneMsg.SceneBuildName);
            }

            if (sceneMsg.OnSceneLoaded != null)
            {
                _onSceneLoaded = sceneMsg.OnSceneLoaded;
            }
        }

        /**
         * 当场景加载完成调用
         */
        private void SeceneManager_sceneLoaded(Scene scene, LoadSceneMode loadSceneMode)
        {
            if (_onSceneLoaded != null)
            {
                _onSceneLoaded();

                _onSceneLoaded = null;
            }
        }
    }
}